/**
 * 增加发起人附言
 */
var pageX = {}
var _storge_key = "";
var dataArea = "#mainBodyArea";

pageX.isSubmitting = false;//重复提交防护
pageX.MAX_INPUT_LENGTH = 500;
pageX.winParams = {}
pageX.cache = {
        postData : {"fileUrlIds":[], 
                    "fileJson" : "[]",
                    "hide" : false,
                    "toSendMsg" : true,
                    "hideToSender" : false
                    }
}

cmp.ready(function() {// 缓存详情页面数据
    
    _storge_key = CollCacheKey.summary.replyComment; 
    
        _initBackEvent();
    cmp.i18n.init(_collPath + "/i18n/", "Collaboration", function(){
        
        //加载数据
        _initPageData(function(){
            
            _fillPage();
            _bindEvent();
            
            document.addEventListener('beforepageredirect', function(e){ 
                _storagePageData();
            });
            
            // cmp.HeaderFixed("#hid", document.querySelector("#content"));
            cmp.description.init(document.querySelector("#content"));
        });
    },$verstion);
});

//存储状态数据
function _storagePageData(){
    
    pageX.cache.datas = CollUtils.formPostData(_$(dataArea));
    cmp.storage.save(_storge_key, cmp.toJSON(pageX.cache), true);
}

/**
 * 加载数据
 */
function _initPageData(onDataReady){
        
         pageX.winParams = cmp.href.getParam();
     
         //缓存加载
        _storge_key = _storge_key + pageX.winParams.cache_subfix;
        pageX.cache = CollUtils.loadCache(_storge_key, true) || pageX.cache;
        
        //缓存加载
        window.summaryBO = CollUtils.loadCache(CollCacheKey.summary.summaryBO + pageX.winParams.cache_subfix);
        
        if(onDataReady){
            onDataReady();
        }
};


function _initBackEvent(){
    
    cmp.backbutton();
    cmp.backbutton.push(_goBack);
    _$("#goBackBtn").addEventListener("tap", _goBack);
}

//返回
function _goBack() {
  cmp.href.back();
}


// 页面布局
function _fillPage() {

    //装载数据
    CollUtils.fillDom(dataArea, pageX.cache.datas);
    
     //国际化title
    _$("title").innerText = cmp.i18n("collaboration.page.lable.opinionReply");
    _$("#content").setAttribute("placeholder", cmp.i18n("collaboration.page.info.inputHuifuComment"));
    
    //加载附件相关信息
    loadAttachment();
    
    //加载开关
    var swContainer = _$("#switch_container");
    _setSwitch("hide", pageX.cache.postData.hide, swContainer);
    _setSwitch("hideToSender", pageX.cache.postData.hideToSender, swContainer);
    //_setSwitch("toSendMsg", pageX.cache.postData.toSendMsg, swContainer);
    
    // 40为常用语这一行的高度
    // _$("#content").style.height = (_$("#comment_div").scrollHeight - 40) + "px";

    //头部加载慢的适配
    _$("#title").style.display = "block";
    _$("#title").style.bottom = "0px";
}


/**
 * 切换开关
 */
function _setSwitch(code, value, container){
    var $switchs = container || _$("#switch_container"),
        sws = _$(".cmp-switch", true, $switchs);
    
    for(var i = 0; i < sws.length; i++){
        var sw = sws[i];
        if(sw.getAttribute("code") == code){
            var isActive = sw.classList.contains("cmp-active");
            if(value != isActive){
                if(value){
                    sw.classList.add("cmp-active");
                    if(code == "hide"){
                        //如果没有勾选隐藏，也不能对发起人隐藏
                        _$("#switch_container .cmp-switch[code='hideToSender']").classList.remove("cmp-disabled");
                    }
                }else{
                    sw.classList.remove("cmp-active");
                }
            }
            break;
        }
    }
}

function loadAttachment(){
    
    var nodeActions = summaryBO.pageConfig.nodeActions || [];
        
    var showAuth = "";
    if(CollUtils.isInArray(nodeActions, "UploadAttachment") && CollUtils.isInArray(nodeActions, "UploadRelDoc")){
        showAuth = -1;
    }else if(CollUtils.isInArray(nodeActions, "UploadAttachment")){
        showAuth = 1;
    }else if(CollUtils.isInArray(nodeActions, "UploadRelDoc")){
        showAuth = 2;
    }
    
    var $attBtn = _$("#attachment_btn");
    if(showAuth != ""){
        $attBtn.classList.remove("display_none");
    }
    
  //附件组件
    var initParam = {
        showAuth : showAuth,
        uploadId : "picture",
        handler : "#attachment_btn",
        //initAttData : null,
        selectFunc : function(result){
            pageX.cache.postData.fileJson = cmp.toJSON(result);
            
            //展示附件数量
            _showAttNum(result.length);
        }
    }
    new SeeyonAttachment({"initParam" : initParam});
}

/**
 * 展示附件数量
 */
function _showAttNum(num, $attBtn){
    
    $attBtn = $attBtn || _$("#attachment_btn");
    
    var text = "", color = "#A2ACC7";
    if(num > 0){
        text = num;
        color = "#3AADFB";
    }
    $attBtn.style.color = color;
    _$("#attCount").innerHTML = text;
}

// 事件绑定
function _bindEvent() {
    
    var $content = _$("#content");
    $content.addEventListener('input', function(){
        CollUtils.fnFontCount("#content", "#fontCount", pageX.MAX_INPUT_LENGTH);
    });
    CollUtils.fnFontCount($content, "#fontCount", pageX.MAX_INPUT_LENGTH);
    
    //开关显示
    _$("#switch_pop_btn").addEventListener('tap', function(e){
        _$("#switch_container").classList.remove("display_none");
    });
    
    //开关事件
    cmp('#switch_container .cmp-switch').each(function() { //循环所有toggle

        this.addEventListener('toggle', function(event) {
            
            var code = this.getAttribute("code"),
                value = this.classList.contains("cmp-active"),
                method;
            if(code == 'hide'){
                var hideToSender = _$("#switch_container .cmp-switch[code='hideToSender']");
                if(value){
                    method = "remove";
                }else{
                    method = "add";
                    if(hideToSender.classList.contains("cmp-active")){
                        hideToSender.classList.remove("cmp-active");
                        with(_$(".cmp-switch-handle", false, hideToSender).style){
                            transform = "";
                            webkitTransform = "";
                        }
                        pageX.cache.postData["hideToSender"] = false;
                    }
                }
                hideToSender.classList[method]("cmp-disabled");
            }
            
            pageX.cache.postData[code] = value;
        });
    });
    
    //影藏开关
    _$("#switch_container").addEventListener('tap', function(e){
        
        /*var className = e.target.getAttribute("class");
        if(!className || className.indexOf("cmp-switch") == -1){
            _$("#switch_container").classList.add("display_none");
        }*/
        if(e.target == this){
            this.classList.add("display_none");
        }
    });
    
    //初始化atWho
    _initAtWho();
    
	_$("#submitBtn").addEventListener("tap", _submit);
}


function _submit(){
    
    //校验空
    if(_checkCommentIsEmpty()){
        return;
    }
    
    if(pageX.isSubmitting){
        return;
    }
    
    _startSubmitting();
        
    //回复意见
    var _oldcomment = CollUtils.getTextDealComment("#content");
    try{
    	var paramData = {};
    	var emojiUtil = cmp.Emoji();
    	pageX.cache.postData.content = emojiUtil.EmojiToString(_oldcomment);
    }catch(e){
    	pageX.cache.postData.content = _oldcomment;
    }
    
    pageX.cache.postData.ctype = 1;
    pageX.cache.postData.affairId = summaryBO.summary.affairId;
    pageX.cache.postData.commentId = pageX.winParams["commentId"];
    //at信息
    pageX.cache.postData.atWhoSelected = _mergeAtWho(pageX.cache.postData.content)
    
    $s.Coll.comment(summaryBO.summary.id, {}, pageX.cache.postData, errorBuilder({
        success : function(result) {
            _goBack();
        },
        error : function(result){
        	//网络问题
        	if(result.code == "-1001"){
        	  	//解除各按钮的绑定
        	  	_removeEvent();
        	}
        }
    }));

}


//检查意见是否允许为空
function _checkCommentIsEmpty(){
    
    var ret = false,
        tempContent = CollUtils.getTextDealComment("#content"),
        isCommentBlank = (tempContent.length == 0) || (tempContent.trim().length == 0);
    
    if(isCommentBlank){
        //{0}内容不能为空
        _alert(cmp.i18n(("collaboration.action.alert.comment_null"), [cmp.i18n("collaboration.page.lable.opinionReply")]));
        ret = true;
    }
    
    return ret;
}

//开始提交
function _startSubmitting(){
    cmp.dialog.loading();
    pageX.isSubmitting = true;
}

//结束提交
function _stopSubmitting(){
    cmp.dialog.loading(false);
    pageX.isSubmitting = false;
}

function _removeEvent(){
	_$("#submitBtn").removeEventListener("tap", _submit);
}